package thread.example4;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 3lock和Condition接口
 */
public class ShareResource {

    private String name;

    private String sex;

    private boolean flag = false;

    private Lock lock = new ReentrantLock();

    private Condition condition = lock.newCondition();

    public   void push(String name, String sex) {
        lock.lock();
        try {
            while (flag) {
                condition.await();
            }
            this.name = name;
            Thread.sleep(10L);
            this.sex = sex;

            flag = true;
            condition.signal();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public  void popup() {
        lock.lock();
        try {
            while (!flag) {
                condition.await();
            }
            System.out.println("name && sex = " + name + "," + sex);
            Thread.sleep(10L);
            flag = false;
            condition.signal();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }


    }

    public static void main(String[] args) {
        ShareResource sr = new ShareResource();
        new Thread(new Product(sr)).start();
        new Thread(new Consumer(sr)).start();



    }
}
